using System;
using System.Linq;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Widgetsphere.WebUtils;
using Widgetsphere.Autos.API.FacetedNavigation;
using Widgetsphere.AutoAggregate.Website.Objects;
using HP.Datastore.Common;
using Widgetsphere.Autos.API;

namespace JacksonHealthCare.ListingSite.WebSite.UserControls
{
    public partial class DimensionFilterDisplayControl : System.Web.UI.UserControl
    {
        private Dictionary<string, string> _orderList = null;

        #region Methods

        public void Populate(IListingResults results, IListingQuery query, IListingResults masterResults, Dictionary<string, string> orderList, string resetURL)
        {
            _orderList = orderList;

            lblReset.Text = "<a class='r' id='facetclearall' href='" + resetURL + "' title='Clear all filters' rel='nofollow'>reset</a>";

            //Group items by dimension
            var dimList = new Dictionary<string, List<IRefinementItem>>();
            foreach (var dvidx in results.Query.DimensionValueList)
            {
                foreach (var dItem in masterResults.DimensionList)
                {
                    var rItem = dItem.RefinementList.FirstOrDefault(x => x.DVIdx == dvidx);
                    if (rItem != null)
                    {
                        if (!dimList.ContainsKey(dItem.Name)) dimList.Add(dItem.Name, new List<IRefinementItem>());
                        dimList[dItem.Name].Add(rItem);
                    }
                }
            }

            var count = 0;

            //Loop through dimensions and create a list of filters
            foreach (var dName in dimList.Keys)
            {
                var dText = masterResults.DimensionList.First(x => x.Name == dName).GetCeleriqDisplayName(_orderList);

                //Create the label
                var l = new Literal();
                l.Text = "<div class=\"ln\"><span class=\"prompt\">" + dText + "</span>: ";

                var rCount = 0;
                foreach (var rItem in dimList[dName])
                {
                    //Create the Dimension Value
                    var fieldValue = (rCount > 0 ? ", &nbsp;" : string.Empty);

                    if (rItem.MinValue != null && rItem.MaxValue != null)
                    {
                        fieldValue += rItem.MinValue.Value.ToString("###,###,###,##0") + " - " + rItem.MaxValue.Value.ToString("###,###,###,##0");
                    }
                    else
                    {
                        fieldValue += rItem.FieldValue;
                    }

                    l.Text += fieldValue;
                    l.Text += this.CreateRemoveLink(this.Request.Url.PathAndQuery, rItem.DVIdx);
                    count++;
                    rCount++;
                }
                l.Text += "</div>";
                pnlFilterDisplay.Controls.Add(l);
            }

            //If there is text filter then add it too
            if (!string.IsNullOrEmpty(results.Query.Keyword))
            {
                //Create the label
                var l = new Literal();
                l.Text = "<div><span class=\"prompt\">Text filter</span>: " + results.Query.Keyword;
                l.Text += this.CreateRemoveLinkNoTextFilter(this.Request.Url.PathAndQuery);
                l.Text += "</div>";
                pnlFilterDisplay.Controls.Add(l);
                count++;
            }

            if (!string.IsNullOrEmpty(query.NonParsedFieldList["srchfn"]))
            {
                //Create the label
                var l = new Literal();
                l.Text = "<div><span class=\"prompt\">First name</span>: " + query.NonParsedFieldList["srchfn"];
                l.Text += this.CreateRemoveLinkFilter(this.Request.Url.PathAndQuery, "srchfn");
                l.Text += "</div>";
                pnlFilterDisplay.Controls.Add(l);
                count++;
            }

            if (!string.IsNullOrEmpty(query.NonParsedFieldList["srchln"]))
            {
                //Create the label
                var l = new Literal();
                l.Text = "<div><span class=\"prompt\">Last name</span>: " + query.NonParsedFieldList["srchln"];
                l.Text += this.CreateRemoveLinkFilter(this.Request.Url.PathAndQuery, "srchln");
                l.Text += "</div>";
                pnlFilterDisplay.Controls.Add(l);
                count++;
            }

            if (!string.IsNullOrEmpty(query.NonParsedFieldList["srchem"]))
            {
                //Create the label
                var l = new Literal();
                l.Text = "<div><span class=\"prompt\">Email</span>: " + query.NonParsedFieldList["srchem"];
                l.Text += this.CreateRemoveLinkFilter(this.Request.Url.PathAndQuery, "srchem");
                l.Text += "</div>";
                pnlFilterDisplay.Controls.Add(l);
                count++;
            }

            var geoFilter = results.Query.FieldFilters.FirstOrDefault(x => x is FieldFilterLocation) as FieldFilterLocation;
            if (geoFilter != null)
            {
                //Create the label
                var l = new Literal();
                var location = results.Query.NonParsedFieldList.Where(x => x.Key == "location").Select(x => x.Value).FirstOrDefault();
                if (string.IsNullOrEmpty(location))
                    location = results.Query.NonParsedFieldList.Where(x => x.Key == "zip").Select(x => x.Value).FirstOrDefault();

                var radius = geoFilter.Radius;
                l.Text = "<div><span class=\"prompt\">Location</span>: " + location + " for " + radius + " miles";
                var url = new ListingQuery(this.Request.Url.PathAndQuery);
                url.FieldFilters.RemoveAll(x => x is FieldFilterLocation);
                url.NonParsedFieldList.RemoveAll(x => x.Key == "zip");
                url.NonParsedFieldList.RemoveAll(x => x.Key == "location");
                url.NonParsedFieldList.RemoveAll(x => x.Key == "rd");
                l.Text += this.CreateRemoveLinkNoTextFilter(url.ToString());
                l.Text += "</div>";
                pnlFilterDisplay.Controls.Add(l);
                count++;
            }

            //Do not show this if there is nothing to show
            if (count == 0)
                this.Visible = false;

            //if (SessionHelper.IsLoggedIn && SessionHelper.CurrentUserType == API.SessionUser.UserTypeConstants.Candidate)
            //{
            //    if (query.DimensionValueList.Count > 0 || query.FieldFilters.Count > 0)
            //    {
            //        pnlSaveFilter.Visible = true;
            //    }
            //}
        }

        private string CreateRemoveLink(string queryString, long dvidx)
        {
            var query = new ListingQuery(queryString);
            query.DimensionValueList.Remove(dvidx);
            return "<a class='trash' title=\"Remove this filter\" rel=\"nofollow\" href=\"" + query.ToString() + "\"><img src=\"/images/trash.gif\" /></a>";
        }

        private string CreateRemoveLinkNoTextFilter(string queryString)
        {
            var query = new ListingQuery(queryString);
            query.Keyword = string.Empty;
            return "<a class='trash' title=\"Remove this filter\" rel=\"nofollow\" href=\"" + query.ToString() + "\"><img src=\"/images/trash.gif\" /></a>";
        }

        private string CreateRemoveLinkFilter(string queryString, string removeFilter)
        {
            var query = new ListingQuery(queryString);
            query.NonParsedFieldList[removeFilter] = string.Empty;
            return "<a class='trash' title=\"Remove this filter\" rel=\"nofollow\" href=\"" + query.ToString() + "\"><img src=\"/images/trash.gif\" /></a>";
        }

        #endregion

    }
}